package me.eleme.anubis.openapi.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.*;


/**
 * 签名工具
 * @author liuzhiyong
 */
@Slf4j
public class SignatureUtil {

    /**
     * 计算签名
     *
     * @param secretKey 秘钥
     * @param toSignPara 签名参数字符串
     * @return 签名后字符串
     */
    public static String genSignature(String secretKey, String toSignPara) {
        return Sha256Util.getsha256(secretKey + toSignPara);
    }

    /**
     * 入参TApiParam按字典序排序
     *
     * <p>正向业务请求接口入参的加签准备工作
     */
    public static String sortGetTokenParams(String appId, String merchantId, String timeStamp,String code) {
        Map<String, String> pMap = new HashMap<>(8);
        pMap.put("grant_type", "authorization_code");
        pMap.put("app_id", appId);
        pMap.put("merchant_id", merchantId);
        pMap.put("timestamp", timeStamp);
        pMap.put("code",code);
        return sortParams(pMap);
    }


    /**
     * 入参按字典序排序
     *
     * <p>刷新token接口加签准备工作
     */
    public static String sortRefreshTokenParams(String appId, String merchantId, String timeStamp,
                                         String refreshToken) {
        Map<String, String> pMap = new HashMap<>(8);
        pMap.put("grant_type", "refresh_token");
        pMap.put("app_id", appId);
        pMap.put("merchant_id", merchantId);
        pMap.put("timestamp", timeStamp);
        pMap.put("refresh_token", refreshToken);
        return sortParams(pMap);
    }


    /**
     * <p>正向业务接口入参的加签准备工作
     */
    public static String sortApiParams(String appId, String merchantId, String timeStamp,
                                       String accessToken, String businessData) {
        Map<String, String> pMap = new HashMap<>(8);
        pMap.put("app_id", appId);
        pMap.put("merchant_id", merchantId);
        pMap.put("timestamp", timeStamp);
        pMap.put("version", "1.0");
        pMap.put("access_token", accessToken);
        pMap.put("business_data", businessData);
        return sortParams(pMap);
    }

    /**
     * 按字典序排列参数
     */
    public static String sortParams(Map<String, String> paramMap) {
        List<String> keys = new ArrayList<>(paramMap.keySet());
        Collections.sort(keys);
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = paramMap.get(key);
            if (value != null && value.length() != 0) {
                content.append(i == 0 ? "" : "&").append(key).append("=").append(value);
            }
        }
        return content.toString();
    }

}
